package com.denlaku.longan.event;

import com.lmax.disruptor.EventHandler;
import org.apache.commons.collections4.ListUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 消息事件处理类，这里只打印消息
 *
 * @author tianx
 */
class MessageEventHandlers implements EventHandler<MessageEvent> {

    private ConcurrentMap<Class<?>, List<MessageEventHandler>> handlerMap = new ConcurrentHashMap<>();

    MessageEventHandlers(List<MessageEventHandler> handlers) {
        for (MessageEventHandler handler : ListUtils.emptyIfNull(handlers)) {
            handlerMap.computeIfAbsent(handler.supportedType(), key -> new Vector<>()).add(handler);
        }
    }

    @Override
    public void onEvent(MessageEvent messageEvent, long sequence, boolean endOfBatch) throws Exception {
        Object content = messageEvent.getContent();
        List<MessageEventHandler> handlers = Optional.ofNullable(content)
            .map(Object::getClass).map(handlerMap::get).orElse(Collections.emptyList());
        for (MessageEventHandler handler : handlers) {
            handler.onEvent(messageEvent, sequence, endOfBatch);
        }
    }
}